<?php
declare (strict_types=1);

namespace app\index\controller;

use app\common\component\Upload;
use app\common\model\Article;
use app\common\model\Order;
use app\common\model\Setting;
use app\common\model\Shop;
use think\App;
use wxpay\WxPay;

class Index extends Base
{

    protected $openId = false;

    public function __construct(App $app)
    {

        parent::__construct($app);
        if ($this->request->action() != 'author') {
            $this->openId = session('openid');
            if (!$this->openId) {
                return $this->oauthLogin('nianbao');
            }
        }
        $this->assign('time', NOW_TIME);
    }

    protected function getRedirectUrl($backurl)
    {
        $getToken = input('token');
        return $this->request->domain() . $this->authorize_url . '?token=' . $getToken . '&backurl=' . base64_encode($backurl);
    }

    public function index(Setting $setting, Order $order)
    {
        $content = $setting->getOneSetting('base');
        $defaultUrl = '/index/index/';
        if ($content['usepage'] == 2) $defaultUrl = '/index/index2/';
        $this->assign('time', NOW_TIME);
        $this->assign('defaultUrl', $defaultUrl);
        $day180 = NOW_TIME - 24 * 3600 * 180;

        //年报是否存在  注销石佛iu存在
        $year = $order->where('openid', $this->openId)->where('type', 1)
            ->where('create_time', '>', $day180)
            ->where('status', '>', 1)->count();
        $exit = $order->where('openid', $this->openId)->where('type', 2)
            ->where('create_time', '>', $day180)
            ->where('status', '>', 1)->count();
        $register = $order->where('openid', $this->openId)->where('type', 3)
            ->where('create_time', '>', $day180)
            ->where('status', '>', 1)->count();
        $change = $order->where('openid', $this->openId)->where('type', 4)
            ->where('create_time', '>', $day180)
            ->where('status', '>', 1)->count();

        $jsparams = $this->getJsParams('nianbao');
        $this->assign('jsparams', $jsparams);

        $this->assign('year', $year);
        $this->assign('exit', $exit);
        $this->assign('register', $register);
        $this->assign('change', $change);
        return $this->fetch();
    }

    public function getOrderOne(Order $order)
    {
        $type = input('type', 1);
        $one = $order->where('openid', $this->openId)->where('type', $type)
            ->whereNull('zheng')->where('status', '>', 1)->find();
        ajaxSuccess($one);
    }


    public function upload()
    {
        $base64 = input('code');
        $result = Upload::instance()->uploadBase64($base64, 'nianbaocc');
        ajaxSuccess($result['data']);
    }

    public function author()
    {
        $code = input('get.code');
        $result = $this->getCodeToAccess('nianbao', $code);
        session('openid', $result['openid']);
        return redirect('/');
    }

    public function create(\app\index\validate\Order $order, Setting $setting, Order $orderModel, Shop $shop)
    {
        $data = $this->request->post(['title' => '', 'name' => '', 'type' => 1, 'idcard' => '', 'mobile' => '']);
        if (!$order->check($data)) ajaxError($order->getError());
        $day180 = NOW_TIME - 24 * 3600 * 180;
        //验证唯一
        $only = $orderModel->where(['title' => $data['title']])
            ->where('create_time', '>', $day180)
            ->where('type', '=', $data['type'])
            ->where('status', '>', 1)->find();
        if ($only) ajaxError('该主体已提交成功');


        $content = $setting->getOneSetting('base');
        $x100 = 1000;
        if ($data['type'] == 1) {
            $price = floatval(bcdiv((string)mt_rand(intval($content['min_nianbao'] * $x100), intval($content['max_nianbao'] * $x100)), (string)$x100, 2));
        } else if ($data['type'] == 2) {
            $price = floatval(bcdiv((string)mt_rand(intval($content['min_zhuxiao'] * $x100), intval($content['max_zhuxiao'] * $x100)), (string)$x100, 2));
        } else if ($data['type'] == 3) {
            $price = floatval(bcdiv((string)mt_rand(intval($content['min_register'] * $x100), intval($content['max_register'] * $x100)), (string)$x100, 2));
        } else if ($data['type'] == 4) {
            $price = floatval(bcdiv((string)mt_rand(intval($content['min_change'] * $x100), intval($content['max_change'] * $x100)), (string)$x100, 2));
        }
        if (in_array($this->openId, ['oYbuU6p_pEreaxQS5aTX-6JvcKi0'])) {
            $price = 0.01;
        }
        $data['shop_id'] = $shop->where('status', 1)->value('id');

        if (!$data['shop_id']) ajaxError('暂无收款商户');
        $data['price'] = $price;
        $data['order_sn'] = createOrderNumber();
        $data['openid'] = session('openid');
        $orderModel->save($data);
        ajaxSuccess($data);
    }

    /**
     * 获取微信支付参数
     */
    public function payParams(Order $order)
    {
        $order->startTrans();
        try {
            //每次进入新订单
            $order_sn = input('order_sn');
            $info = $order->where('order_sn', $order_sn)->find();
            if ($info['status'] == 2) throw new \Exception('已支付');
            $total_fee = intval(bcmul($info['price'], (string)100));
            if (in_array($this->openId, ['oYbuU6p_pEreaxQS5aTX-6JvcKi0'])) {
                $total_fee = 1;
            }

            $params = [
                'body' => ['年报通道', '注销通道', '营业执照注册', '营业执照变更'][$info['type'] - 1],
                'order_sn' => $info['order_sn'],
                'total_fee' => $total_fee,
                'openid' => $info['openid'],
                'notify_url' => $this->request->domain() . '/index/notify/notify'
            ];
            $result = WxPay::instance()->jspayParams($params);
            if ($result['errCode']) {
                throw new \Exception($result['message']);
            }
            $order->commit();
            ajaxSuccess($result['data']);
        } catch (\Exception $exception) {
            $order->rollback();
            ajaxError($exception->getMessage());
        }
    }


    public function article(Article $article)
    {
        $list = $article->where('status', 1)->select();
        ajaxSuccess($list);
    }

    public function info(Article $article)
    {
        $id = input('get.id');
        $info = $article->where('id', $id)->find();
        ajaxSuccess($info);
    }

    /**
     * @name 保存身份证
     * @param Order $order
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function idcard(Order $order)
    {
        $data = $this->request->post(['order_sn', 'zheng', 'fan']);
        if (!$data['order_sn']) ajaxError('订单不存在');
        if (!$data['zheng'] || !$data['fan']) ajaxError('请上传身份证照片');
        $info = $order->where('order_sn', $data['order_sn'])->find();
        if (!$info || $info['openid'] != $this->openId) ajaxError('无权限或已失效' . $this->openId);
        if ($info['status'] == 1) ajaxError('订单未支付');
        if ($info['zheng']) ajaxError('已上传');
        $info->zheng = $data['zheng'];
        $info->fan = $data['fan'];
        $info->save();
        ajaxSuccess($info);
    }

    public function orderinfo(Order $order)
    {
        $id = input('order_sn');
        $info = $order->where('order_sn', $id)->find();
        ajaxSuccess($info);
    }

}
